package com.cskaoyan.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.crypto.digest.MD5;
import com.cskaoyan.bean.BaseData;
import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.administrators.*;
import com.cskaoyan.bean.administrators.bo.AdminCreateBO;
import com.cskaoyan.bean.administrators.bo.RoleCreateBO;
import com.cskaoyan.bean.administrators.bo.RolePermissionsBO;
import com.cskaoyan.bean.administrators.bo.RoleUpdateBO;
import com.cskaoyan.bean.administrators.vo.*;
import com.cskaoyan.bean.promotion.storage.PicStorage;
import com.cskaoyan.bean.promotion.storage.UploadPicStorageVO;
import com.cskaoyan.mapper.*;
import com.cskaoyan.util.DateUtils;
import com.cskaoyan.util.Md5HashUtil;
import com.cskaoyan.util.PageUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.cskaoyan.util.UUIDUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 系统管理
 * @Author: 徐能雄
 * @Date: 2021/9/15 17:03
 */
@Service
public class AdministratorsServiceImpl implements AdministratorsService {

    @Autowired
    AdminAdminMapper adminAdminMapper;
    @Autowired
    LogMapper logMapper;
    @Autowired
    NoticeMapper noticeMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    AdminStorageMapper adminStorageMapper;
    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    PicStorageMapper storageMapper;

    //上传文件本地路径
    @Value("${spring.servlet.multipart.location}")
    String filePath;
    //拼接pic得url
    @Value("${Info.host}")
    String picUrl;

    @Override
    public BaseData<AdminListVO> adminList(BaseParam param, String username) {
        //获取param参数里的分页数据page和limit
        PageUtil.start(param);
        AdminExample example = new AdminExample();
        //拼接降序查询参数add_time desc
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        AdminExample.Criteria criteria = example.createCriteria();
        //username非空则继续进行模糊查询
        if (username != null && !"".equals(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        //此处需做string和Integer[]的类型转化，通过typehandler自动实现
        List<Admin> admins = adminAdminMapper.selectByExample(example);
        List<AdminListVO> adminListVOS = new ArrayList<>();
        for (Admin admin : admins) {
            AdminListVO adminListVO = new AdminListVO(admin.getAvatar(), admin.getId(), admin.getRoleIds(), admin.getUsername());
            adminListVOS.add(adminListVO);
        }
        PageInfo<AdminListVO> adminPageInfo = new PageInfo<>(adminListVOS);
        BaseData<AdminListVO> adminBaseData = new BaseData<>(adminPageInfo, adminListVOS);
        return adminBaseData;
    }

    @Override
    public RoleOptionsVO roleOptions() {
        List<Role> roleList = roleMapper.selectByExample(null);
        ArrayList<RoleVO> roleVOS = new ArrayList<>();
        for (Role role : roleList) {
            RoleVO roleVO = new RoleVO(role.getId(), role.getName());
            roleVOS.add(roleVO);
        }
        RoleOptionsVO roleOptionsVO = new RoleOptionsVO(roleVOS, roleList.size());
        return roleOptionsVO;
    }

    @Override
    public AdminCreateVO adminCreate(AdminCreateBO adminCreateBO) throws RuntimeException {
        //获取当前时间
        DateTime now = DateTime.now();
        //判断用户名是否重复，并决定是否允许注册
        Integer i = adminAdminMapper.selectIdByName(adminCreateBO.getUsername());
        if (i != null) {
            boolean b = adminAdminMapper.selectDeleteByName(adminCreateBO.getUsername());
            if (!b) throw new RuntimeException("该用户已存在,无法重复注册");
            else {
                adminAdminMapper.deleteByPrimaryKey(i);
            }
        }
        String password = Md5HashUtil.Md5encryption(adminCreateBO.getPassword());
        //String password= (adminCreateBO.getPassword(),BCrypt.gensalt());
        Admin admin = Admin.builder().username(adminCreateBO.getUsername()).password(password).avatar(adminCreateBO.getAvatar()).roleIds(adminCreateBO.getRoleIds()).addTime(now).updateTime(now).deleted(false).build();
        int insert = adminAdminMapper.insert
                (admin);
        if (insert != 1) throw new RuntimeException("新增用户失败 ,请重试");
        //插入成功后获取id
        Integer id = adminAdminMapper.selectIdByName(adminCreateBO.getUsername());
        //获取账号信息
        Admin admin1 = adminAdminMapper.selectByPrimaryKey(id);
        //时间改为string类型
        AdminCreateVO adminCreateVO = new AdminCreateVO(admin1.getPassword(), admin1.getRoleIds(), admin1.getAddTime().toString(), admin1.getUpdateTime().toString(), admin1.getId(), admin1.getAvatar(), admin1.getUsername());
        return adminCreateVO;
    }

    @Override
    public int adminDelete(AdminCreateBO deleteCreateBO) {
        int i = adminAdminMapper.deleteByPrimaryKey(deleteCreateBO.getId());
        if (i > 0) {
            return 200;
        } else {
            return 404;
        }
    }

    @Override
    public AdminUpdateVO adminUpdate(AdminCreateBO updateCreateBO) throws RuntimeException {
        Admin admin = adminAdminMapper.selectByPrimaryKey(updateCreateBO.getId());
        Integer integer = adminAdminMapper.selectIdByName(updateCreateBO.getUsername());
        if (integer != null && !admin.getId().equals(integer)) {
            throw new RuntimeException("该用户名已存在，请重新修改");
        }
        DateTime now = DateTime.now();
        admin.setUpdateTime(now);
        admin.setAvatar(updateCreateBO.getAvatar());

        admin.setPassword(Md5HashUtil.Md5encryption(updateCreateBO.getPassword()));
        admin.setRoleIds(updateCreateBO.getRoleIds());
        admin.setUsername(updateCreateBO.getUsername());
        int update = adminAdminMapper.updateByPrimaryKey(admin);
        if (update != 1) throw new RuntimeException("修改失败 ,请重试");
        Integer id = adminAdminMapper.selectIdByName(admin.getUsername());
        Admin admin1 = adminAdminMapper.selectByPrimaryKey(id);
        AdminUpdateVO adminUpdateVO = new AdminUpdateVO(admin1.getAvatar(), admin1.getId(), admin1.getRoleIds(), admin1.getUpdateTime().toString(), admin1.getUsername());
        return adminUpdateVO;
    }

    @Override
    public BaseData<Log> logList(BaseParam param, String username) {
        PageUtil.start(param);
        LogExample example = new LogExample();
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        LogExample.Criteria criteria = example.createCriteria();
        if (username != null && !"".equals(username)) {
            criteria.andAdminLike("%" + username + "%");
        }
        List<Log> logs = logMapper.selectByExample(example);

        PageInfo<Log> logPageInfo = new PageInfo<>(logs);
        BaseData<Log> logBaseData = new BaseData<>(logPageInfo, logs);
        return logBaseData;
    }

    @Override
    public void logWriter(BaseRespVo result, String username, Date lastLoginTime, Integer type, String action, boolean status,String result2,String comment) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest();
        //String ip = request.getRemoteAddr();//地址
        String ip = request.getLocalAddr();
        String requestURI = request.getRequestURI();
        DateTime now = DateTime.now();//添加修改时间
        String errmsg = "";//result
        try {
            errmsg =result.getErrmsg();//result
        } catch (Exception e) {
            e.printStackTrace();
        }

        if ("成功".equals(errmsg)){ status=true; }else { status=false;}

        Log log = Log.builder().action(action).addTime(now).updateTime(now).admin(username)
                .ip(ip).type(type).status(status).result(result2).comment(comment).deleted(false).build();
        logMapper.insert(log);
    }

    @Override
    public BaseData<RoleListVO> roleList(BaseParam param, String name) {
        PageUtil.start(param);
        RoleExample example = new RoleExample();
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        RoleExample.Criteria criteria = example.createCriteria();
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        List<Role> roleList = roleMapper.selectByExample(example);
        List<RoleListVO> roleListVOS = new ArrayList<>();
        for (Role role : roleList) {
            RoleListVO roleListVO = new RoleListVO(role.getDeleted(), role.getAddTime().toString(), role.getName(), role.getUpdateTime().toString(), role.getId(), role.getEnabled(), role.getDesc());
            roleListVOS.add(roleListVO);
        }
        PageInfo<RoleListVO> roleListVOPageInfo = new PageInfo<>(roleListVOS);
        BaseData<RoleListVO> roleListVOBaseData = new BaseData<>(roleListVOPageInfo, roleListVOS);
        return roleListVOBaseData;
    }

    @Override
    public RoleCreateVO roleCreate(RoleCreateBO roleCreateBO) {
        //获取当前时间
        DateTime now = DateTime.now();
        //判断用户名是否重复，并决定是否允许注册
        Integer i = roleMapper.selectIdByName(roleCreateBO.getName());
        if (i != null) {
            boolean b = roleMapper.selectDeleteByName(roleCreateBO.getName());
            if (!b) throw new RuntimeException("该角色已存在");
            else {
                roleMapper.deleteByPrimaryKey(i);
            }
        }
        Role role = Role.builder().name(roleCreateBO.getName()).desc(roleCreateBO.getDesc()).enabled(true).addTime(now).updateTime(now).deleted(false).build();
        int insert = roleMapper.insert(role);
        if (insert != 1) throw new RuntimeException("新增角色失败 ,请重试");
        //插入成功后获取id
        Integer id = roleMapper.selectIdByName(roleCreateBO.getName());
        //获取账号信息
        Role role1 = roleMapper.selectByPrimaryKey(id);
        //时间改为string类型
        RoleCreateVO roleCreateVO = new RoleCreateVO(role1.getAddTime().toString(), role1.getName(), role1.getUpdateTime().toString(), role1.getId(), role1.getDesc());
        return roleCreateVO;
    }

    @Override
    public int roleDelete(RoleUpdateBO roleDeleteBO) {
        int i = roleMapper.deleteByPrimaryKey(roleDeleteBO.getId());
        if (i > 0) {
            return 200;
        } else {
            return 404;
        }
    }

    @Override
    public int roleUpdate(RoleUpdateBO roleUpdateBO) {
        Role role = roleMapper.selectByPrimaryKey(roleUpdateBO.getId());
        Integer integer = roleMapper.selectIdByName(roleUpdateBO.getName());
        if (integer != null && !role.getId().equals(integer)) {
            throw new RuntimeException("该角色已存在，请重新修改");
        }
        DateTime now = DateTime.now();
        role.setName(roleUpdateBO.getName());
        role.setDesc(roleUpdateBO.getDesc());
        role.setUpdateTime(now);
        int update = roleMapper.updateByPrimaryKey(role);
        if (update == 1) {
            return 200;
        } else {
            return 404;
        }
    }

    @Override
    public RolePermissionsVO roleGetPermissions(Integer roleId) throws JsonProcessingException {
        String rp = "{\"systemPermissions\":[{\"id\":\"商品管理\",\"label\":\"商品管理\",\"children\":[{\"id\":\"商品管理\",\"label\":\"商品管理\",\"children\":[{\"id\":\"admin:goods:read\",\"label\":\"详情\",\"api\":\"GET /admin/goods/detail\"},{\"id\":\"admin:goods:update\",\"label\":\"编辑\",\"api\":\"POST /admin/goods/update\"},{\"id\":\"admin:goods:list\",\"label\":\"查询\",\"api\":\"GET /admin/goods/list\"},{\"id\":\"admin:goods:delete\",\"label\":\"删除\",\"api\":\"POST /admin/goods/delete\"},{\"id\":\"admin:goods:create\",\"label\":\"上架\",\"api\":\"POST /admin/goods/create\"}]},{\"id\":\"评论管理\",\"label\":\"评论管理\",\"children\":[{\"id\":\"admin:comment:list\",\"label\":\"查询\",\"api\":\"GET /admin/comment/list\"},{\"id\":\"admin:comment:delete\",\"label\":\"删除\",\"api\":\"POST /admin/comment/delete\"}]}]},{\"id\":\"商场管理\",\"label\":\"商场管理\",\"children\":[{\"id\":\"订单管理\",\"label\":\"订单管理\",\"children\":[{\"id\":\"admin:order:read\",\"label\":\"详情\",\"api\":\"GET /admin/order/detail\"},{\"id\":\"admin:order:reply\",\"label\":\"订单商品回复\",\"api\":\"POST /admin/order/reply\"},{\"id\":\"admin:order:refund\",\"label\":\"订单退款\",\"api\":\"POST /admin/order/refund\"},{\"id\":\"admin:order:ship\",\"label\":\"订单发货\",\"api\":\"POST /admin/order/ship\"},{\"id\":\"admin:order:list\",\"label\":\"查询\",\"api\":\"GET /admin/order/list\"},{\"id\":\"admin:order:delete\",\"label\":\"订单删除\",\"api\":\"POST /admin/order/delete\"}]},{\"id\":\"类目管理\",\"label\":\"类目管理\",\"children\":[{\"id\":\"admin:category:update\",\"label\":\"编辑\",\"api\":\"POST /admin/category/update\"},{\"id\":\"admin:category:list\",\"label\":\"查询\",\"api\":\"GET /admin/category/list\"},{\"id\":\"admin:category:read\",\"label\":\"详情\",\"api\":\"GET /admin/category/read\"},{\"id\":\"admin:category:delete\",\"label\":\"删除\",\"api\":\"POST /admin/category/delete\"},{\"id\":\"admin:category:create\",\"label\":\"添加\",\"api\":\"POST /admin/category/create\"}]},{\"id\":\"通用问题\",\"label\":\"通用问题\",\"children\":[{\"id\":\"admin:issue:update\",\"label\":\"编辑\",\"api\":\"POST /admin/issue/update\"},{\"id\":\"admin:issue:list\",\"label\":\"查询\",\"api\":\"GET /admin/issue/list\"},{\"id\":\"admin:issue:delete\",\"label\":\"删除\",\"api\":\"POST /admin/issue/delete\"},{\"id\":\"admin:issue:create\",\"label\":\"添加\",\"api\":\"POST /admin/issue/create\"}]},{\"id\":\"关键词\",\"label\":\"关键词\",\"children\":[{\"id\":\"admin:keyword:update\",\"label\":\"编辑\",\"api\":\"POST /admin/keyword/update\"},{\"id\":\"admin:keyword:list\",\"label\":\"查询\",\"api\":\"GET /admin/keyword/list\"},{\"id\":\"admin:keyword:read\",\"label\":\"详情\",\"api\":\"GET /admin/keyword/read\"},{\"id\":\"admin:keyword:delete\",\"label\":\"删除\",\"api\":\"POST /admin/keyword/delete\"},{\"id\":\"admin:keyword:create\",\"label\":\"添加\",\"api\":\"POST /admin/keyword/create\"}]},{\"id\":\"品牌管理\",\"label\":\"品牌管理\",\"children\":[{\"id\":\"admin:brand:update\",\"label\":\"编辑\",\"api\":\"POST /admin/brand/update\"},{\"id\":\"admin:brand:list\",\"label\":\"查询\",\"api\":\"GET /admin/brand/list\"},{\"id\":\"admin:brand:read\",\"label\":\"详情\",\"api\":\"GET /admin/brand/read\"},{\"id\":\"admin:brand:delete\",\"label\":\"删除\",\"api\":\"POST /admin/brand/delete\"},{\"id\":\"admin:brand:create\",\"label\":\"添加\",\"api\":\"POST /admin/brand/create\"}]}]},{\"id\":\"用户管理\",\"label\":\"用户管理\",\"children\":[{\"id\":\"用户收藏\",\"label\":\"用户收藏\",\"children\":[{\"id\":\"admin:wxcollect:list\",\"label\":\"查询\",\"api\":\"GET /admin/wxcollect/list\"}]},{\"id\":\"搜索历史\",\"label\":\"搜索历史\",\"children\":[{\"id\":\"admin:history:list\",\"label\":\"查询\",\"api\":\"GET /admin/history/list\"}]},{\"id\":\"收货地址\",\"label\":\"收货地址\",\"children\":[{\"id\":\"admin:address:list\",\"label\":\"查询\",\"api\":\"GET /admin/address/list\"}]},{\"id\":\"意见反馈\",\"label\":\"意见反馈\",\"children\":[{\"id\":\"admin:feedback:list\",\"label\":\"查询\",\"api\":\"GET /admin/feedback/list\"}]},{\"id\":\"会员管理\",\"label\":\"会员管理\",\"children\":[{\"id\":\"admin:user:list\",\"label\":\"详情\",\"api\":\"GET /admin/user/detail\"},{\"id\":\"admin:user:list\",\"label\":\"编辑\",\"api\":\"POST /admin/user/update\"},{\"id\":\"admin:user:list\",\"label\":\"查询\",\"api\":\"GET /admin/user/list\"}]},{\"id\":\"用户足迹\",\"label\":\"用户足迹\",\"children\":[{\"id\":\"admin:footprint:list\",\"label\":\"查询\",\"api\":\"GET /admin/footprint/list\"}]}]},{\"id\":\"推广管理\",\"label\":\"推广管理\",\"children\":[{\"id\":\"团购管理\",\"label\":\"团购管理\",\"children\":[{\"id\":\"admin:groupon:read\",\"label\":\"详情\",\"api\":\"GET /admin/groupon/listRecord\"},{\"id\":\"admin:groupon:update\",\"label\":\"编辑\",\"api\":\"POST /admin/groupon/update\"},{\"id\":\"admin:groupon:list\",\"label\":\"查询\",\"api\":\"GET /admin/groupon/list\"},{\"id\":\"admin:groupon:delete\",\"label\":\"删除\",\"api\":\"POST /admin/groupon/delete\"},{\"id\":\"admin:groupon:create\",\"label\":\"添加\",\"api\":\"POST /admin/groupon/create\"}]},{\"id\":\"广告管理\",\"label\":\"广告管理\",\"children\":[{\"id\":\"admin:ad:update\",\"label\":\"编辑\",\"api\":\"POST /admin/ad/update\"},{\"id\":\"admin:ad:list\",\"label\":\"查询\",\"api\":\"GET /admin/ad/list\"},{\"id\":\"admin:ad:read\",\"label\":\"详情\",\"api\":\"GET /admin/ad/read\"},{\"id\":\"admin:ad:delete\",\"label\":\"删除\",\"api\":\"POST /admin/ad/delete\"},{\"id\":\"admin:ad:create\",\"label\":\"添加\",\"api\":\"POST /admin/ad/create\"}]},{\"id\":\"优惠券管理\",\"label\":\"优惠券管理\",\"children\":[{\"id\":\"admin:coupon:listuser\",\"label\":\"查询用户\",\"api\":\"GET /admin/coupon/listuser\"},{\"id\":\"admin:coupon:update\",\"label\":\"编辑\",\"api\":\"POST /admin/coupon/update\"},{\"id\":\"admin:coupon:list\",\"label\":\"查询\",\"api\":\"GET /admin/coupon/list\"},{\"id\":\"admin:coupon:read\",\"label\":\"详情\",\"api\":\"GET /admin/coupon/read\"},{\"id\":\"admin:coupon:delete\",\"label\":\"删除\",\"api\":\"POST /admin/coupon/delete\"},{\"id\":\"admin:coupon:create\",\"label\":\"添加\",\"api\":\"POST /admin/coupon/create\"}]},{\"id\":\"专题管理\",\"label\":\"专题管理\",\"children\":[{\"id\":\"admin:topic:batch-delete\",\"label\":\"批量删除\",\"api\":\"POST /admin/topic/batch-delete\"},{\"id\":\"admin:topic:update\",\"label\":\"编辑\",\"api\":\"POST /admin/topic/update\"},{\"id\":\"admin:topic:list\",\"label\":\"查询\",\"api\":\"GET /admin/topic/list\"},{\"id\":\"admin:topic:read\",\"label\":\"详情\",\"api\":\"GET /admin/topic/read\"},{\"id\":\"admin:topic:delete\",\"label\":\"删除\",\"api\":\"POST /admin/topic/delete\"},{\"id\":\"admin:topic:create\",\"label\":\"添加\",\"api\":\"POST /admin/topic/create\"}]},{\"id\":\"通知管理\",\"label\":\"通知管理\",\"children\":[{\"id\":\"admin:notice:batch-delete\",\"label\":\"批量删除\",\"api\":\"POST /admin/notice/batch-delete\"},{\"id\":\"admin:notice:update\",\"label\":\"编辑\",\"api\":\"POST /admin/notice/update\"},{\"id\":\"admin:notice:read\",\"label\":\"详情\",\"api\":\"GET /admin/notice/read\"},{\"id\":\"admin:notice:delete\",\"label\":\"删除\",\"api\":\"POST /admin/notice/delete\"},{\"id\":\"admin:notice:create\",\"label\":\"添加\",\"api\":\"POST /admin/notice/create\"}]}]},{\"id\":\"配置管理\",\"label\":\"配置管理\",\"children\":[{\"id\":\"小程序配置\",\"label\":\"小程序配置\",\"children\":[{\"id\":\"admin:config:wx:list\",\"label\":\"详情\",\"api\":\"GET /admin/config/wx\"},{\"id\":\"admin:config:wx:updateConfigs\",\"label\":\"编辑\",\"api\":\"POST /admin/config/wx\"}]},{\"id\":\"运费配置\",\"label\":\"运费配置\",\"children\":[{\"id\":\"admin:config:express:list\",\"label\":\"详情\",\"api\":\"GET /admin/config/express\"},{\"id\":\"admin:config:express:updateConfigs\",\"label\":\"编辑\",\"api\":\"POST /admin/config/express\"}]},{\"id\":\"商场配置\",\"label\":\"商场配置\",\"children\":[{\"id\":\"admin:config:mall:list\",\"label\":\"详情\",\"api\":\"GET /admin/config/mall\"},{\"id\":\"admin:config:mall:updateConfigs\",\"label\":\"编辑\",\"api\":\"POST /admin/config/mall\"}]},{\"id\":\"订单配置\",\"label\":\"订单配置\",\"children\":[{\"id\":\"admin:config:order:list\",\"label\":\"详情\",\"api\":\"GET /admin/config/order\"},{\"id\":\"admin:config:order:updateConfigs\",\"label\":\"编辑\",\"api\":\"POST /admin/config/order\"}]}]},{\"id\":\"商城管理\",\"label\":\"商城管理\",\"children\":[{\"id\":\"售后管理\",\"label\":\"售后管理\",\"children\":[{\"id\":\"admin:aftersale:reject\",\"label\":\"审核拒绝\",\"api\":\"POST /admin/aftersale/reject\"},{\"id\":\"admin:aftersale:refund\",\"label\":\"退款\",\"api\":\"POST /admin/aftersale/refund\"},{\"id\":\"admin:aftersale:recept\",\"label\":\"审核通过\",\"api\":\"POST /admin/aftersale/recept\"},{\"id\":\"admin:aftersale:batch-recept\",\"label\":\"批量通过\",\"api\":\"POST /admin/aftersale/batch-recept\"},{\"id\":\"admin:aftersale:batch-reject\",\"label\":\"批量拒绝\",\"api\":\"POST /admin/aftersale/batch-reject\"},{\"id\":\"admin:aftersale:list\",\"label\":\"查询\",\"api\":\"GET /admin/aftersale/list\"}]}]},{\"id\":\"统计管理\",\"label\":\"统计管理\",\"children\":[{\"id\":\"用户统计\",\"label\":\"用户统计\",\"children\":[{\"id\":\"admin:stat:user\",\"label\":\"查询\",\"api\":\"GET /admin/stat/user\"}]},{\"id\":\"订单统计\",\"label\":\"订单统计\",\"children\":[{\"id\":\"admin:stat:order\",\"label\":\"查询\",\"api\":\"GET /admin/stat/order\"}]},{\"id\":\"商品统计\",\"label\":\"商品统计\",\"children\":[{\"id\":\"admin:stat:goods\",\"label\":\"查询\",\"api\":\"GET /admin/stat/goods\"}]}]},{\"id\":\"系统管理\",\"label\":\"系统管理\",\"children\":[{\"id\":\"对象存储\",\"label\":\"对象存储\",\"children\":[{\"id\":\"admin:storage:update\",\"label\":\"编辑\",\"api\":\"POST /admin/storage/update\"},{\"id\":\"admin:storage:list\",\"label\":\"查询\",\"api\":\"GET /admin/storage/list\"},{\"id\":\"admin:storage:read\",\"label\":\"详情\",\"api\":\"POST /admin/storage/read\"},{\"id\":\"admin:storage:delete\",\"label\":\"删除\",\"api\":\"POST /admin/storage/delete\"},{\"id\":\"admin:storage:create\",\"label\":\"上传\",\"api\":\"POST /admin/storage/create\"}]},{\"id\":\"管理员管理\",\"label\":\"管理员管理\",\"children\":[{\"id\":\"admin:admin:update\",\"label\":\"编辑\",\"api\":\"POST /admin/admin/update\"},{\"id\":\"admin:admin:list\",\"label\":\"查询\",\"api\":\"GET /admin/admin/list\"},{\"id\":\"admin:admin:read\",\"label\":\"详情\",\"api\":\"GET /admin/admin/read\"},{\"id\":\"admin:admin:delete\",\"label\":\"删除\",\"api\":\"POST /admin/admin/delete\"},{\"id\":\"admin:admin:create\",\"label\":\"添加\",\"api\":\"POST /admin/admin/create\"}]},{\"id\":\"角色管理\",\"label\":\"角色管理\",\"children\":[{\"id\":\"admin:role:permission:update\",\"label\":\"权限变更\",\"api\":\"POST /admin/role/permissions\"},{\"id\":\"admin:role:update\",\"label\":\"角色编辑\",\"api\":\"POST /admin/role/update\"},{\"id\":\"admin:role:list\",\"label\":\"角色查询\",\"api\":\"GET /admin/role/list\"},{\"id\":\"admin:role:read\",\"label\":\"角色详情\",\"api\":\"GET /admin/role/read\"},{\"id\":\"admin:role:delete\",\"label\":\"角色删除\",\"api\":\"POST /admin/role/delete\"},{\"id\":\"admin:role:permission:get\",\"label\":\"权限详情\",\"api\":\"GET /admin/role/permissions\"},{\"id\":\"admin:role:create\",\"label\":\"角色添加\",\"api\":\"POST /admin/role/create\"}]},{\"id\":\"操作日志\",\"label\":\"操作日志\",\"children\":[{\"id\":\"admin:log:list\",\"label\":\"查询\",\"api\":\"GET /admin/log/list\"}]},{\"id\":\"通知管理\",\"label\":\"通知管理\",\"children\":[{\"id\":\"admin:notice:list\",\"label\":\"查询\",\"api\":\"GET /admin/notice/list\"}]}]},{\"id\":\"其他\",\"label\":\"其他\",\"children\":[{\"id\":\"权限测试\",\"label\":\"权限测试\",\"children\":[{\"id\":\"index:permission:write\",\"label\":\"权限写\",\"api\":\"POST /admin/index/write\"},{\"id\":\"index:permission:read\",\"label\":\"权限读\",\"api\":\"GET /admin/index/read\"}]}]}],\"assignedPermissions\":[]}\n";

        List<String> p = permissionMapper.selectPermission(roleId);

        ObjectMapper mapper = new ObjectMapper();
        RolePermissionsVO rolePermissionsVO = mapper.readValue(rp, RolePermissionsVO.class);
        rolePermissionsVO.setAssignedPermissions(p);
        return rolePermissionsVO;
    }

    @Override
    public int rolePostPermissions(RolePermissionsBO rolePermissionsBO) {
        List<String> permissions = rolePermissionsBO.getPermissions();
        int insert = 0;
        for (String s : permissions) {
            Permission permission = new Permission(null, rolePermissionsBO.getRoleId(), s, DateTime.now(), DateTime.now(), false);
            permissionMapper.insert(permission);
            insert++;
        }
        if (insert == permissions.size()) {
            return 200;
        } else {
            return 404;
        }
    }

    @Override
    public BaseData<StorageListVO> storageList(BaseParam param, String key, String name) {
        PageUtil.start(param);
        StorageExample example = new StorageExample();
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        StorageExample.Criteria criteria = example.createCriteria();
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (key != null && !"".equals(key)) {
            criteria.andKeyEqualTo(key);
        }
        List<Storage> storages = adminStorageMapper.selectByExample(example);
        List<StorageListVO> storageListVOS = new ArrayList<>();
        for (Storage storage : storages) {
            StorageListVO storageListVO = new StorageListVO(storage.getDeleted(), storage.getSize(), storage.getAddTime().toString(), storage.getName(), storage.getUpdateTime().toString(), storage.getId(), storage.getType(), storage.getKey(), storage.getUrl());
            storageListVOS.add(storageListVO);
        }
        PageInfo<StorageListVO> roleListVOPageInfo = new PageInfo<>(storageListVOS);
        BaseData<StorageListVO> roleListVOBaseData = new BaseData<>(roleListVOPageInfo, storageListVOS);
        return roleListVOBaseData;
    }

    @Override
    public Storage storageCreate(MultipartFile myFile) throws IOException {
        String url = "";
        String fileType = myFile.getContentType();
        String updateTime = DateTime.now().toDateStr();
        String uuid = UUID.randomUUID().toString();
        byte[] bytes = myFile.getBytes();
        String collision = MD5.create().digestHex(bytes);
        List<Storage> storages = adminStorageMapper.selectByKey(collision);
        return null;
    }

    @Override
    public int storageDelete(StorageListVO storageUpdateBO) {
        int i = adminStorageMapper.deleteByPrimaryKey(storageUpdateBO.getId());
        if (i == 1) {
            return 200;
        } else {
            return 404;
        }
    }

    @Override
    public StorageListVO storageUpdate(StorageListVO storageUpdateBO) {
        Storage storage = adminStorageMapper.selectByPrimaryKey(storageUpdateBO.getId());
        storage.setName(storageUpdateBO.getName());
        storage.setUpdateTime(DateTime.now());
        int i = adminStorageMapper.updateByPrimaryKey(storage);
        if (i != 1) throw new RuntimeException("修改出错，请重试");
        return storageUpdateBO;
    }


    /**
     * 上传照片的逻辑
     *
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public UploadPicStorageVO setPic(MultipartFile file) throws IOException {

        String name = file.getOriginalFilename();
        //属性
        String property = name.substring(name.lastIndexOf(".") + 1);
        String key = UUIDUtil.getUUID() + "." + property;
        //以日期命名文件夹，方便查寻
        String dateFile = DateUtils.dateSimpleFormat(new Date());
        File file1 = new File(filePath + dateFile, key);

        if (!file1.getParentFile().exists()) {
            file1.getParentFile().mkdirs();
        }

        PicStorage picStorage = new PicStorage();
        picStorage.setDeleted(false);
        Date addTime = new Date();
        picStorage.setAddTime(addTime);
        picStorage.setType(file.getContentType());
        picStorage.setName(name);
        picStorage.setSize((int) file.getSize());
        picStorage.setUpdateTime(addTime);
        picStorage.setUrl(picUrl + dateFile + "/" + key);
        picStorage.setKey(key);
        storageMapper.insertByHand(picStorage);
        //保存文件
        file.transferTo(file1);
        return new UploadPicStorageVO(picStorage);


    }

    @Override
    public Admin getAdmin(String username) {

        return adminAdminMapper.getAdminByUsername(username);
    }

    @Override
    public List<String> getRoles(Admin admin) {
        Integer[] roleIds = admin.getRoleIds();
        ArrayList<String> roles = new ArrayList<>();
        for (Integer roleId : roleIds) {
            String role = roleMapper.getRoleById(roleId);
            roles.add(role);
        }

        return roles;
    }

    @Override
    public List<String> getPerms(Admin admin) {
        Integer[] roleIds = admin.getRoleIds();
        ArrayList<String> perms = new ArrayList<>();

        for (Integer roleId : roleIds) {
            perms.addAll(permissionMapper.getPermsByRoleId(roleId));
        }

        return perms;


    }


}
